<?php
namespace app\common\model;

use think\Validate;
use think\Db;
use think\model\concern\SoftDelete;
use think\facade\Log;

class DeviceLogRepair extends Common
{
    const STATUS_WAITAUDIT = 1;       //状态 等待审核
    const STATUS_SUCCESS = 2;       //状态 审核通过
    const STATUS_REFUSE = 3;        //状态 审核拒绝

    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';

    /**
     * 创建售后单
     * @param $user_id
     * @param $log_id //发起报修的设备日志ID
     * @param array $images
     * @param string $reason //售后理由
     * @param bool $formId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function toAdd($user_id, $log_id, $images = [], $reason = "", $formId = false)
    {
        $result = [
            'status' => false,
            'data'   => [],
            'msg'    => ''
        ];

        //更新订单状态
        $deviceLog = new DeviceLog();
        $device_info = $deviceLog->where(['id'=>$log_id])->find(); 
        if(!$device_info){
            return error_code(13105);
        }
        $bill_id = $device_info['bill_id'];
  
        $awhere[] = ['bill_id', 'eq', $bill_id];
        $awhere[] = ['user_id', 'eq', $user_id];
        $awhere[] = ['status', 'eq', self::STATUS_WAITAUDIT];
        $flag     = $this->where($awhere)->find();
        if ($flag) {
            return error_code(13103);
        }

        $data['repair_id'] = get_sn(5);

        //判断图片是否大于系统限定
        if (count($images) > config('zlserver.image_max')) {
            return error_code(10006);
        }

        Db::startTrans();
        try {
            $data['bill_id'] = $bill_id;
            $data['user_id']  = $user_id;
            $data['reason']   = htmlentities($reason);

            $this->save($data);
            //保存售后图片
            if ($images) {
                foreach ($images as $v) {
                    $rel_img['repair_id'] = $data['repair_id'];
                    $rel_img['image_id']      = $v;
                    $rel_arr[]                = $rel_img;
                }
                $deviceLogRepairImages = new DeviceLogRepairImages();
                $deviceLogRepairImages->saveAll($rel_arr);
            }

            //微信消息模板
            if ($formId) {
                $templateMessageModel = new TemplateMessage();
                $message              = [
                    'type'    => $templateMessageModel::TYPE_REPAIR,
                    'code'    => $bill_id,
                    'form_id' => $formId,
                    'status'  => $templateMessageModel::SEND_STATUS_NO
                ];
                $templateMessageModel->addSend($message);
            }
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        $result['status'] = true;
        $result['data']   = $data;
        return $result;
    }


    /**
     * 平台审核通过或者审核不通过
     * 如果审核通过了，是退款单的话，自动生成退款单，并做订单完成状态，如果是退货的话，自动生成退款单和退货单，如果
     * @param $id
     * @param $status
     * @param string $mark 
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function audit($id, $status, $mark = "")
    {
        $result = [
            'status' => false,
            'data'   => [],
            'msg'    => ''
        ];
        $where  = [
            'repair_id' => $id,
            'status'        => self::STATUS_WAITAUDIT
        ];
        $info   = $this->where($where)->find();
        if (!$info) {
            return error_code(13104);
        }

        Db::startTrans();
        try {
            $data['status'] = $status;
            $data['mark']   = $mark;
            $this->where($where)->data($data)->update();

            //审核通过的话，有退款的，生成退款单，根据最新的items生成退货单,并做订单的状态更改
            if ($status == self::STATUS_SUCCESS) {
                //更新订单状态
                $deviceLog = new DeviceLog();
                $order_data['status'] = $deviceLog::STATUS_REFUND;
                $deviceLog->where(['bill_id' => $info['bill_id'], 'status' => $deviceLog::STATUS_PAYED])->data($order_data)->update();
                // 售后审核通过后操作
                hook('aftersalesSuccess', $info);
            }

            Db::commit();
            //发送售后审核消息
            //$eventData                      = $orderInfo->toArray();
            $eventData['repair_status'] = ($status == self::STATUS_SUCCESS) ? '审核通过' : '审核拒绝';
            $eventData['repair_id']         = $id;
            $eventData['mark']              = $mark;
            sendMessage($info['user_id'], 'repair_pass', $eventData);

            $result['status'] = true;
        } catch (\Exception $e) {
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }

        return $result;

    }
 
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $list       = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data       = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code']  = 0;
        $re['msg']   = '';
        $re['count'] = $list->total();
        $re['data']  = $data;
        $re['sql']   = $this->getLastSql();

        return $re;
    }


    /**
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if (isset($post['bill_id']) && $post['bill_id'] != "") {
            $where[] = ['bill_id', 'like', '%' . $post['bill_id'] . '%'];
        }
        if (isset($post['repair_id']) && $post['repair_id'] != "") {
            $where[] = ['repair_id', 'like', '%' . $post['repair_id'] . '%'];
        }
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['repair_id', 'in', $post['id']];
        }
        if (isset($post['date']) && $post['date'] != "") {
            $date    = explode(' 到 ', $post['date']);
            $where[] = ['ctime', 'between time', [$date[0] . ' 00:00:00', $date[1] . ' 23:59:59']];
        }
        if (isset($post['mobile']) && $post['mobile'] != "") {
            if ($user_id = get_user_id($post['mobile'])) {
                $where[] = ['user_id', 'eq', $user_id];
            } else {
                $where[] = ['user_id', 'eq', '99999999'];       //如果没有此用户，那么就赋值个数值，让他查不出数据
            }
        }

        if (isset($post['status']) && $post['status'] != "") {
            $where[] = ['status', 'eq', $post['status']];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = 'repair_id desc';
        return $result;
    }


    /**
     * 根据查询结果，格式化数据
     * @author tony
     * @param $list  array格式的collection
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach ($list as $k => $v) {
            if ($v['status']) {
                $list[$k]['status_name'] = config('params.repair')['status'][$v['status']];
            }
            if ($v['user_id']) {
                $list[$k]['user_id'] = format_mobile(get_user_info($v['user_id']));
            }
  
            if ($v['ctime']) {
                $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            } 
        }
        return $list;
    }
 
    /**
     * 获取设备报修信息
     * @return array
     */
    public function getDeviceRepairInfo($bill_id)
    {
        $result = ['status' => false, 'msg' => '' , 'data' => ''];
        $deviceRepairInfo = $this->where(['bill_id' => $bill_id])->find();

        if(!$deviceRepairInfo) {
            return error_code(10002);
        }
 
        $result['data'] = $deviceRepairInfo; 
        return $result;
    } 
    
    /**
     * 前端接口，分页
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListApi($data)
    {
        $result = [
            'status' => true,
            'data'   => [],
            'msg'    => ''
        ];

        $where['user_id']             = $data['user_id'];
        $result['data']['list']       = $this::with(['order' => ['items']])
            ->where($where)
            ->order('utime desc')
            ->page($data['page'], $data['limit'])
            ->select()->hidden(['order' => ['isdel']]);
        $total                        = $this
            ->where($where)
            ->order('utime desc')
            ->count();
        $result['data']['page']       = $data['page'];
        $result['data']['limit']      = $data['limit'];
        $result['data']['total_page'] = ceil($total / $data['limit']);
        return $result;
    }


    /**
     * 获取售后单信息
     * @param $user_id
     * @param $bill_id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($user_id, $bill_id)
    {
        $result                 = [
            'status' => false,
            'data'   => [],
            'msg'    => ''
        ];
        $where['user_id']       = $user_id;
        $where['bill_id']       = $bill_id;
        $info                   = $this::with('images')
            ->where($where)
            ->find();
        if (!$info) {
            return error_code(13223);
        }

        $imageList = array(); 
        foreach ($info['images'] as $k => $v) {
            $imageList[] = _sImage($v['image_id']);
        }

        $info['imageList'] = $imageList;

        if ($info['status']) {
            $info['status'] = config('params.repair')['status'][$info['status']];
        }
        
        $result['status'] = true;
        $result['data']   = $info;

        return $result;
    }


    /**
     * @return int|string
     */
    public function getCount()
    {
        $where[] = ['status', 'eq', self::STATUS_WAITAUDIT];
        $count   = $this->where($where)->count();
        return $count ? $count : 0;
    }


    /**
     * @return \think\model\relation\HasMany
     */
    public function images()
    {
        return $this->hasMany('DeviceLogRepairImages', 'repair_id', 'repair_id');
    }
    
    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'     => 'repair_id',
                'desc'   => '售后单号',
                'modify' => 'convertString'
            ],
            [
                'id'     => 'bill_id',
                'desc'   => '订单编号',
                'modify' => 'convertString'
            ],
            [
                'id'   => 'status_name',
                'desc' => '状态',
            ],
            [
                'id'   => 'user_id',
                'desc' => '用户',
            ],
            [
                'id'   => 'reason',
                'desc' => '原因',

            ],
            [
                'id'   => 'ctime',
                'desc' => '申请时间',

            ],
        ];
    }
 
    /**
     * 获取csv数据
     * @param $post
     * @return array
     */
    public function getCsvData($post)
    {
        $result   = [
            'status' => false,
            'data'   => [],
            'msg'    => '无可导出数据',

        ];
        $header   = $this->csvHeader();
        $userData = $this->getExportList($post);

        if ($userData['count'] > 0) {
            $tempBody = $userData['data'];
            $body     = [];
            $i        = 0;

            foreach ($tempBody as $key => $val) {
                $i++;
                foreach ($header as $hk => $hv) {
                    if (isset($val[$hv['id']]) && $val[$hv['id']] && isset($hv['modify'])) {
                        if (function_exists($hv['modify'])) {
                            $body[$i][$hk] = $hv['modify']($val[$hv['id']]);
                        }
                    } elseif (isset($val[$hv['id']]) && !empty($val[$hv['id']])) {
                        $body[$i][$hk] = $val[$hv['id']];
                    } else {
                        $body[$i][$hk] = '';
                    }
                }
            }
            $result['status'] = true;
            $result['msg']    = '导出成功';
            $result['data']   = $body;
            return $result;
        } else {
            //失败，导出失败
            return $result;
        }
    }
 
    /**
     * 导出验证
     * @param array $params
     * @return array
     */
    public function exportValidate(&$params = [])
    {
        $result = [
            'status' => false,
            'data'   => [],
            'msg'    => '参数丢失',
        ];
        return $result;
    }
 
    //导出格式
    public function getExportList($post = [])
    {
        $return_data = [
            'status' => false,
            'msg'    => '获取失败',
            'data'   => '',
            'count'  => 0
        ];
        $where       = [];
        if (isset($post['log_id']) && $post['log_id'] != "") {
            $where[] = ['log_id', 'like', '%' . $post['log_id'] . '%'];
        }
        if (isset($post['repair_id']) && $post['repair_id'] != "") {
            $where[] = ['repair_id', 'like', '%' . $post['repair_id'] . '%'];
        }
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['repair_id', 'in', $post['id']];
        }
        if (isset($post['date']) && $post['date'] != "") {
            $date    = explode(' 到 ', $post['date']);
            $where[] = ['ctime', 'between time', [$date[0] . ' 00:00:00', $date[1] . ' 23:59:59']];
        }
        if (isset($post['mobile']) && $post['mobile'] != "") {
            if ($user_id = get_user_id($post['mobile'])) {
                $where[] = ['user_id', 'eq', $user_id];
            } else {
                $where[] = ['user_id', 'eq', '99999999'];       //如果没有此用户，那么就赋值个数值，让他查不出数据
            }
        }

        if (isset($post['status']) && $post['status'] != "") {
            $where[] = ['status', 'eq', $post['status']];
        }
        if (isset($post['type']) && $post['type'] != "") {
            $where[] = ['type', 'eq', $post['type']];
        }

        $list = $this->where($where)
            ->order('repair_id desc')
            ->select();

        if ($list) {
            $count = $this->where($where)->count();
            foreach ($list as $k => $v) {
                if ($v['status']) {
                    $list[$k]['status_name'] = config('params.bill_aftersales')['status'][$v['status']];
                }
                if ($v['user_id']) {
                    $list[$k]['user_id'] = format_mobile(get_user_info($v['user_id']));
                }

                if ($v['ctime']) {
                    $list[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
                }
                if ($v['type']) {
                    $list[$k]['type'] = config('params.bill_aftersales')['type'][$v['type']];
                }
            }
            $return_data = [
                'status' => true,
                'msg'    => '获取成功',
                'data'   => $list,
                'count'  => $count
            ];
        }
        return $return_data;
    }


    /**
     * 统计用户的售后数量
     * @param $user_id
     * @param $status
     * @return float|string
     */
    public function getUserAfterSalesNum($user_id, $status)
    {
        $where[] = ['user_id', 'eq', $user_id];
        $where[] = ['status', 'in', $status];
        return $this->where($where)->count();
    }


    /**
     * @param $log_id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderAfterSaleStatus($log_id)
    {
        $where[] = ['log_id', 'eq', $log_id];
        $info    = $this->where($where)->find();
        if ($info) {
            if ($info['status'] == self::STATUS_WAITAUDIT) {
                $text = '<span style="color:#ff7159;">待审核</span>';
            } else if ($info['status'] == self::STATUS_SUCCESS) {
                if ($info['type'] == self::TYPE_REFUND) {
                    $refundModel = new BillRefund();
                    $text        = '<span style="color:#ff7159;">' . $refundModel->getAftersalesStatus($info['repair_id']) . '</span>';
                } else if ($info['type'] == self::TYPE_RESHIP) {
                    $refundModel = new BillRefund();
                    $refund      = $refundModel->getAftersalesStatus($info['repair_id']);
                    $reshipModel = new BillReship();
                    $reship      = $reshipModel->getAftersalesStatus($info['repair_id']);
                    $text        = '<span style="color:#ff7159;">' . $reship . ',' . $refund . '</span>';
                } else {
                    $text = '<span style="color:#ff7159;">状态异常</span>';
                }
            } else if ($info['status'] == self::STATUS_REFUSE) {
                $text = '<span style="color:#ff7159;">审核拒绝</span>';
            } else {
                $text = '<span style="color:#ff7159;">状态异常</span>';
            }
        } else {
            $text = '';
        }

        return $text;
    }
}